package com.aabte.lota.auth.auth.shiro;

import com.aabte.lota.auth.account.entity.User;
import com.aabte.lota.auth.account.exception.UserNotFoundException;
import com.aabte.lota.auth.account.service.UserService;
import com.google.common.collect.Sets;
import javax.annotation.Resource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/5
 */
public class UsernamePasswordRealm extends AuthorizingRealm {

  private static final String REALM_NAME = UsernamePasswordRealm.class.getSimpleName();

  @Resource private UserService userService;

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof UsernamePasswordToken;
  }

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String username = (String) principals.getPrimaryPrincipal();
    // 根据用户名查找角色，请根据需求实现

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

    // 根据username查询角色
    authorizationInfo.setRoles(Sets.newHashSet("admin", "superadmin"));

    // 根据username查询权限
    authorizationInfo.setStringPermissions(Sets.newHashSet("system:*"));

    return authorizationInfo;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    String username = usernamePasswordToken.getUsername();

    User user;
    try {
      user = userService.queryUserByUsername(username);
    } catch (UserNotFoundException e) {
      throw new UnknownAccountException(e);
    }

    Object principal = user;

    // 用户是否被禁用
    return new SimpleAuthenticationInfo(
        principal, user.getPassword(), new Sha512Hash(username), REALM_NAME);
  }
}
